<template>
  <div class="dashboard">
    <div class="stats-container">
      <div class="stat-card">
        <h3>已连接学生</h3>
        <p class="stat-value">{{ stats.connectedCount || 0 }}</p>
      </div>
      <div class="stat-card">
        <h3>已交卷学生</h3>
        <p class="stat-value">{{ stats.submittedCount || 0 }}</p>
      </div>
    </div>

    <div class="content-grid">
      <StudentList :students="connectedStudents" />
      <ExamControl @upload="handleUpload" />
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, onUnmounted} from 'vue'
import { useExamStore } from '@/stores/examStore'
import StudentList from '@/views/StudentList.vue'
import ExamControl from '@/views/ExamControl.vue'

const examStore = useExamStore()
const stats = ref({
  connectedCount: 0,
  submittedCount: 0
})
const connectedStudents = ref([])

// 获取统计数据
const fetchStats = async () => {
  try {
    console.log('正在请求统计数据...')
    const response = await fetch('http://localhost:8098/stats', {
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
      },
      credentials: 'include' // 如果需要携带cookie
    })

    console.log('响应状态:', response.status)

    // 检查Content-Type是否为JSON
    const contentType = response.headers.get('content-type')
    if (!contentType || !contentType.includes('application/json')) {
      const text = await response.text()
      throw new Error(`期望JSON响应，但得到: ${text.substring(0, 100)}...`)
    }

    const data = await response.json()
    console.log('获取到的统计数据:', data)
    stats.value = data
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 显示错误提示给用户
  }
}

// 获取学生列表
const fetchStudents = async () => {
  try {
    console.log('正在请求学生列表...')
    const response = await fetch('http://localhost:8098/student/list')
    console.log(response)
    console.log('响应状态:', response.status)

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }

    const data = await response.json()
    console.log('获取到的学生列表:', data)
    connectedStudents.value = data
  } catch (error) {
  }
}

// 初始化数据
onMounted(() => {
  fetchStats()
  fetchStudents()

  // 设置定时刷新
  const intervalId = setInterval(() => {
    fetchStats()
    fetchStudents()
  }, 30000) // 每5秒刷新一次

  // 组件卸载时清除定时器
  onUnmounted(() => {
    clearInterval(intervalId)
  })
})

const handleUpload = async () => {
  try {
    const result = await examStore.packageAndUploadPapers()
    alert(`上传成功: ${result.message}`)
  } catch (error) {
    alert(`上传失败: ${error.message}`)
  }
}
</script>

<style scoped>
/* 保持原有样式不变 */
.dashboard {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.stats-container {
  display: flex;
  gap: 1rem;
}

.stat-card {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-card h3 {
  margin: 0 0 0.5rem 0;
  font-size: 1rem;
  color: #666;
}

.stat-value {
  margin: 0;
  font-size: 2rem;
  font-weight: bold;
  color: #2c3e50;
}

.content-grid {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 1rem;
}

@media (max-width: 768px) {
  .content-grid {
    grid-template-columns: 1fr;
  }
}
</style>